package info.marlan.util;

import info.marlan.sipgate.WidgetProvider;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import android.util.Log;




public class VCardtools {
	
	private static final byte ESCAPE_CHAR = '=';
	public static String readVCardName(String entry){
		if(entry==null){
			return null;
		}
		String name = null;
		ByteArrayInputStream fis = new ByteArrayInputStream(entry.getBytes());
		try {
			name = VCardtools.readVCardName(fis);
		} catch (IOException e) {
			Log.e(WidgetProvider.LOGTAG, e.getMessage());
		}
		return name;
	}
	
	public static String readVCardName(InputStream fis) throws IOException {
		String name = "";

		while (true) {
			String line = readLine(fis);
			if (line.length() < 1) {
				break;
			}
			if (line.equalsIgnoreCase("END:VCARD")) {
				break;
			}
		
			if (line.startsWith("FN")) {
				name = decodeQuotedPrintable(line.substring(line.indexOf(":") + 1));
			}
		}
		return name;
	}
	/*
	public static void readVCard(InputStream fis) throws IOException {
		String name = "";
		String notes = "";
		Vector<String[]> phones = new Vector<String[]>();
		Vector<String[]> emails = new Vector<String[]>();
		Vector<String[]> sites = new Vector<String[]>();
		while (true) {
			String line = readLine(fis);
			if (line.length() < 1) {
				break;
			}
			if (line.equalsIgnoreCase("END:VCARD")) {
				break;
			}
			if (line.startsWith("NOTE")) {
				notes = line.substring(line.indexOf(":") + 1);
			} else if (line.startsWith("N")) {
				name = line.substring(line.indexOf(":") + 1);
			} else if (line.startsWith("FN")) {
				name = decodeQuotedPrintable(line.substring(line.indexOf(":") + 1));
			} else if (line.startsWith("TEL")) {
				String phoneType = "OTHER";
				if (line.indexOf(";") >= 0) {
					phoneType = line.substring(line.indexOf(";") + 1, line
							.indexOf(":"));
				}
				String phone = line.substring(line.indexOf(":") + 1);
				String[] str = { phoneType, phone };
				phones.add(str);
			} else if (line.startsWith("EMAIL")) {
				String emailType = "INTERNET";
				if (line.indexOf(";") >= 0) {
					emailType = line.substring(line.indexOf(";") + 1, line
							.indexOf(":"));
					if (emailType.indexOf(";") >= 0) {
						emailType = emailType.substring(0, emailType
								.indexOf(";") + 1);
					}
				}
				String email = line.substring(line.indexOf(":") + 1);
				String[] str = { emailType, email };
				emails.add(str);
			} else if (line.startsWith("URL")) {
				String siteType = "WORK";
				if (line.indexOf(";") >= 0) {
					siteType = line.substring(line.indexOf(";") + 1, line
							.indexOf(":"));
				}
				String site = line.substring(line.indexOf(":") + 1);
				String[] str = { siteType, site };
				sites.add(str);
			}
		}
		System.out.println("----------------------------");
		System.out.println(name);
		System.out.println(notes);
		System.out.println(phones);
		System.out.println(emails);
		System.out.println(sites);
		System.out.println("----------------------------");
	}

*/
	public static String readLine(InputStream inputstream) throws IOException {
		ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
		for (int i1 = 0; (i1 = inputstream.read()) != -1 && i1 != 10;)
			if (i1 != 13)
				bytearrayoutputstream.write((byte) i1);

		return getUtf8String(bytearrayoutputstream.toByteArray());
	}

	public static String getUtf8String(byte[] iArr) {
		return (getUtf8String(iArr, 0, iArr.length));
	}

	public static String getUtf8String(byte[] iArr, int j, int k) {
		try {
			ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
			DataOutputStream dataoutputstream = new DataOutputStream(
					bytearrayoutputstream);
			dataoutputstream.writeShort(k);
			dataoutputstream.write(iArr, j, k);
			DataInputStream datainputstream = new DataInputStream(
					new ByteArrayInputStream(bytearrayoutputstream
							.toByteArray()));
			return (datainputstream.readUTF());
		} catch (IOException ioexception) {
			return ("");
		}
	}
	public static String decodeQuotedPrintable(String str){
		if(str==null){
			return "";
		}
		try {
	
			return new String(VCardtools.decodeQuotedPrintable(str.getBytes("US-ASCII")),"ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}
	
	
    public static final byte[] decodeQuotedPrintable(byte[] bytes)  {
        if (bytes == null) {
            return null;
        }
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        for (int i = 0; i < bytes.length; i++) {
            int b = bytes[i];
            if (b == ESCAPE_CHAR) {
                try {
                    int u = VCardtools.digit16(bytes[++i]);
                    int l = VCardtools.digit16(bytes[++i]);
                    buffer.write((char) ((u << 4) + l));
                } catch (ArrayIndexOutOfBoundsException e) {
                 //   throw new Exception("Invalid quoted-printable encoding", e);
                }
            } else {
                buffer.write(b);
            }
        }
        return buffer.toByteArray();
    }
    
    static int digit16(byte b) {
        int i = Character.digit((char) b, 16);
        if (i == -1) {
          //  throw new Exception("Invalid URL encoding: not a valid digit (radix : " + b);
        }
        return i;
    }

}
